<template>
  <RouterView></RouterView>
</template>

<script setup>
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getApiUrl } from './config/api.js'

const router = useRouter()

// 全局token验证
onMounted(() => {
  // 检查token有效性
  const validateToken = async () => {
    const token = localStorage.getItem('token')
    if (token && router.currentRoute.value.meta.requiresAuth) {
      try {
        const response = await fetch(getApiUrl('/auth/validate'), {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          localStorage.removeItem('token')
          localStorage.removeItem('loginUsername')
          router.push('/')
        }
      } catch (error) {
        localStorage.removeItem('token')
        localStorage.removeItem('loginUsername')
        router.push('/')
      }
    }
  }
  
  validateToken()
})
</script>